<?php
/**
 * @author: liaofei<136327134@qq.com>
 * @day: 2020/7/10
 */

namespace app\services\pay;

use app\dao\order\StoreOrderDao;
use app\services\BaseServices;
use app\services\user\UserServices;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 余额支付
 * Class YuePayServices
 * @package app\services\pay
 */
class YuePayServices extends BaseServices
{

    /**
     *
     * StoreOrderSuccessServices constructor.
     * @param StoreOrderDao $dao
     */
    public function __construct(StoreOrderDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 订单余额支付
     * @param array $orderInfo
     * @param int $uid
     * @return bool[]|string[]
     */
    public function yuePointOrderPay(array $orderInfo, int $uid) {
        if (!$orderInfo) {
            return ['status' => 'pay_no_order', 'msg' => '订单不存在'];
        }
        /** @var UserServices $userService */
        $userService = app()->make(UserServices::class);
        $userInfo = $userService->getUserInfo($uid);
        if ($userInfo['now_money'] < $orderInfo['pay_price']){
            return ['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])];
        }
        if ($userInfo['points'] < $orderInfo['use_integral']){
            return ['status' => 'pay_deficiency', 'msg' => '积分不足' . floatval($orderInfo['use_integral'])];
        }

        Db::startTrans();
        $res[] = $userService->bcDec($userInfo['uid'], 'now_money', $orderInfo['pay_price'], 'uid');
        $res[] = $userService->bcDec($userInfo['uid'], 'points', $orderInfo['use_integral'], 'uid');
        /** @var PayServices $payService */
        $payService = app()->make(PayServices::class);
        if ($payService->pointPay($orderInfo, $userInfo)) {
            Db::rollback();
            return ['status' => 'pay_error', 'msg' => '余额支付失败'];
        }
        Db::commit();
        return ['status' => true];
    }

    /**
     * 订单余额支付
     * @param array $orderInfo
     * @param int $uid
     * @return bool[]|string[]
     */
    public function yueOrderPay(array $orderInfo, int $uid) {
        if (!$orderInfo) {
            return ['status' => 'pay_no_order', 'msg' => '订单不存在'];
        }
        /** @var UserServices $userService */
        $userService = app()->make(UserServices::class);
        $userInfo = $userService->getUserInfo($uid);
        if ($userInfo['now_money'] < $orderInfo['pay_price']){
            return ['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval($orderInfo['pay_price'])];
        }

        Db::startTrans();
        $res[] = $userService->bcDec($userInfo['uid'], 'now_money', $orderInfo['pay_price'], 'uid');
        /** @var PayServices $payService */
        $payService = app()->make(PayServices::class);
        if ($payService->joinPinkPay($orderInfo, $userInfo)) {
            Db::rollback();
            return ['status' => 'pay_error', 'msg' => '余额支付失败'];
        }
        Db::commit();
        return ['status' => true];
    }
}
